package com.redrose.flutterdemo.camera;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.hardware.Camera;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.redrose.flutterdemo.R;
import com.redrose.flutterdemo.bean.Photo;
import com.redrose.flutterdemo.bean.Time;
import com.redrose.flutterdemo.databinding.ActivityCameraBinding;
import com.redrose.flutterdemo.ui.activitys.BaseActivity;
import com.redrose.flutterdemo.utils.BitmapCallBack;
import com.redrose.flutterdemo.utils.GlideUtils;
import com.redrose.flutterdemo.utils.LogUtils;
import com.redrose.flutterdemo.utils.MySensorHelper;
import com.redrose.flutterdemo.utils.SPUtils;
import com.redrose.flutterdemo.utils.ToastUtil;
import com.redrose.flutterdemo.utils.ToolUtils;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.litepal.crud.DataSupport;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Desc:
 * Author: RedRose
 * Date: 2019/3/20
 * Email: yinsxi@163.com
 */
@Route(path = "/activity/camera")
public class CameraActivity extends BaseActivity<ActivityCameraBinding> implements BitmapCallBack {
    private boolean showLocation = false;
    private PopupWindow mPopWindow;
    private List<Photo> mPhotoList;
    private Time mTime;
//    /**
//     * 是否旋转图片
//     * true 表示当前Activity 处于横屏，false：当前处于竖屏
//     */
//    private boolean mIsRotate = false;
    /**
     * 重力传感器监听
     * 横着 竖着状态
     */
    private MySensorHelper mMySensor;


    @Override
    public int setLayout() {
        initState();

        return R.layout.activity_camera;
    }
    @Override
    public void initData() {
        mBinding.setClickHandler(new ClickHandler());
        mMySensor = new MySensorHelper(this);
        mMySensor.enable();
        int mode = SPUtils.getInt("Flash_mode");
        initFlashMode(mode);
        mBinding.cameraPreview.setBitmapCallback(this);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Calendar calendar = Calendar.getInstance();
        String format = sdf.format(calendar.getTime());
        mTime = new Time();
        mTime.setClassId(Long.parseLong(format));
        mTime.setDay(calendar.get(Calendar.DAY_OF_MONTH));
        mTime.setYear(calendar.get(Calendar.YEAR));
        mTime.setMonth(calendar.get(Calendar.MONTH) + 1);
        mPhotoList = new ArrayList<>();
        hideToolBar();
    }

    private void showPopWindow(View view) {
        mPopWindow = new PopupWindow(view, ToolUtils.dp2px(mContext.getApplicationContext(),
                200), ToolUtils.dp2px(mContext.getApplicationContext(), 200));
        mPopWindow.setFocusable(true);
//        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3F51B5")));
        mPopWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mPopWindow.setOutsideTouchable(true);
        mPopWindow.update();
        if (showLocation) {
            mPopWindow.showAsDropDown(mBinding.saveText);
        } else {
            mPopWindow.showAsDropDown(mBinding.preText);
        }
    }

    /**
     * 显示支持保存的分辨率
     */
    private void showSupportSize(List<Camera.Size> list) {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View view = inflater.inflate(R.layout.pop_size_layout, null);
        RecyclerView recycleView = view.findViewById(R.id.recycle_size);
        initRecycle(recycleView);
        SizeAdapter mAdapter = new SizeAdapter(mContext, R.layout.size_item, list);
        recycleView.setAdapter(mAdapter);
        showPopWindow(view);
    }



    private void initRecycle(RecyclerView recyclerView) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        //设置Adapter
//        recyclerView.setAdapter(recycleAdapter);
        //设置分隔线
//        recyclerView.addItemDecoration(new DividerGridItemDecoration(this));
        //设置增加或删除条目的动画
        recyclerView.setItemAnimator(new DefaultItemAnimator());
    }

    @Override
    public void backByte(byte[] data) {
        GlideUtils.loadByte(mBinding.photoList, data);
        ToolUtils.saveImageFile(data, mPhotoList, mIsRotate);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Calendar calendar = Calendar.getInstance();
        String format = sdf.format(calendar.getTime());
        List<Time> times = DataSupport.where("classId = ?", format).find(Time.class);
        mTime.setPhotoList(mPhotoList);
        if (times.size() == 0) {
            mTime.save();
        }
    }

    /**
     * Desc: 相机页面，拍摄照片保存分辨率 显示适配器
     * author: RedRose
     * Date: 2019/4/1
     * Email: yinsxi@163.com
     */
    private class SizeAdapter extends CommonAdapter<Camera.Size> {

        private SizeAdapter(Context context, int layoutId, List<Camera.Size> datas) {
            super(context, layoutId, datas);
        }

        @Override
        protected void convert(ViewHolder holder, Camera.Size size, int position) {
            LogUtils.d("----redrose 装载数据测试 ----");
            TextView textView = holder.getView(R.id.size_text);
            String sizeString = String.format("%d * % d", size.width, size.height);
            textView.setText(sizeString);
            if (showLocation) {
                textView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        CameraUtil.getInstance().setSaveSize(size);
                        if (mPopWindow != null) {
                            mPopWindow.dismiss();
                            mPopWindow = null;
                        }
                        ToastUtil.show(mContext, size.width + "x" + size.height);
                    }
                });
            }
        }
    }

    private void initFlashMode(int mode) {
        if (mode == CameraUtil.FLASH_AUTO) {
            mBinding.flashlight.setImageResource(R.mipmap.flash_auto);
        } else if (mode == CameraUtil.FLASH_OFF) {
            mBinding.flashlight.setImageResource(R.mipmap.flash_off);
        } else if (mode == CameraUtil.FLASH_ON) {
            mBinding.flashlight.setImageResource(R.mipmap.flash_on);
        }
        CameraUtil.getInstance().setFlashMode(mode);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMySensor.disable();
        LogUtils.e(TAG, " ---onDestroy---");
    }
    /**
     * 是否旋转图片
     */
    @Override
    public void setIsRotate(boolean isRotate) {
        if(mIsRotate == isRotate){
            return;
        }
        this.mIsRotate = isRotate;
        if (mIsRotate) {
            CameraUtil.getInstance().setRotateDegree(0);
        }else {
            CameraUtil.getInstance().setRotateDegree(90);
        }
    }
    @Override
    public boolean getIsRotate(){
        return mIsRotate;
    }

    public class ClickHandler {
        //拍照
        public void takePhoto(){
            mBinding.cameraPreview.takePhoto();
        }
        //切换闪光灯模式
        public void switchFlashMode(){
            int mode = SPUtils.getInt("Flash_mode");
            if (mode == CameraUtil.FLASH_AUTO) {
                mode = CameraUtil.FLASH_OFF;
            } else if (mode == CameraUtil.FLASH_OFF) {
                mode = CameraUtil.FLASH_ON;
            } else if (mode == CameraUtil.FLASH_ON) {
                mode = CameraUtil.FLASH_AUTO;
            }
            SPUtils.put("Flash_mode", mode);
            initFlashMode(mode);
        }
        public void changeSize(){
            //设置保存图片的分辨率
            showLocation = true;
            showSupportSize(CameraUtil.getInstance().getPictureSizeList());
        }
        //打开图库
        public void queryAllPhoto(){
            ARouter.getInstance()
                    .build("/activity/images")
                    .navigation();
        }
        //打开当前拍摄的照片图库
        public void queryCurrentPhoto(){
            int size = mPhotoList.size();
            if (size == 0) {
                ToastUtil.show(mContext, "还未拍摄照片，可以点击右侧查看所有照片");
                return;
            }
            Bundle bundle = new Bundle();
            bundle.putSerializable("photoList", (ArrayList<Photo>) mPhotoList);
            ARouter.getInstance()
                    .build("/activity/preview")
                    .withBundle("data",bundle)
                    .navigation();
        }
    }
}
